package ui;


import Main.Main;
import component.*;
import component.MenuBar;
import util.GsonUils;
import util.ImageUtils;
import util.ScreenUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;


/**
 * @author zhongwen
 * @description IDE的主界面
 * @date 2021-12-08 21:12
 */
public class HomePage {
    // 声明窗口
    public static final JFrame jf = new JFrame("CodeEasy");

   // 声明主编辑面板
    private final TablePane jTab = new TablePane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);

    // 声明顶部菜单栏
    private final TopToolBar topToolBar = new TopToolBar(jTab);

    // 声明菜单栏
    private final MenuBar menuBar = new MenuBar(jTab, topToolBar);



    // 代码编辑界面和模拟运行框的组合
    private VerticalSplitPane vsp;

    // 模拟终端面板
    private final ConsolePane p2 = new ConsolePane();

    // 代码编辑面板
    private final JPanel p1 = new JPanel();


    public void init(){


        p1.setLayout(new BorderLayout());
        p1.add(topToolBar, BorderLayout.NORTH);
        p1.add(jTab, BorderLayout.CENTER);

        vsp = new VerticalSplitPane(p1,p2);
        topToolBar.setVsp(vsp);
        jf.add(vsp, BorderLayout.CENTER);
        jf.add(new BottomBar(vsp), BorderLayout.SOUTH);
        jf.setJMenuBar(menuBar);
        jf.setIconImage(ImageUtils.getImage("java.png"));
        jf.setSize(ScreenUtils.getScreenWidth() - 20, ScreenUtils.getScreenHeight() - 20);
        jf.setLocationRelativeTo(null);
        // 关闭界面时对所有未存储的文本进行处理
        jf.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosed(e);
                int count = jTab.getTabCount();
                for(int i = 0; i < count; i++){
                    ClassTab tabI = (ClassTab) jTab.getTabComponentAt(0);
                    jTab.setSelectedIndex(0);
                    tabI.needSaveFile();
                    jTab.remove(0);
                }
                List<String> recentFiles = new ArrayList<>();
                for(String s : topToolBar.getRecentlyAdded()){
                    recentFiles.add(s);
                }
                Main.configurationBean.setRecentFiles(recentFiles);
                GsonUils.objectToString(Main.configurationBean);
            }
        });
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
    }


}
